package ProbabilitiesCalcs;

import java.util.ArrayList;
//import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import NWPackage.Calculations;
import NWPackage.OneSettingDistMatrix;
import NWPackage.ProbabilityCell;
import NWPackage.RankDist;
import NW_Dynamic.DynamicHelper;

public class DynamicProbCalc {
	
	public static ProbabilityCell DynamicProbCalcFunc(String agent, List<String> permutation, OneSettingDistMatrix inputMatrix)
	{
		//Calc the permutation Recursivly
		String per = Calculations.StringFromList(permutation);
		//ProbabilityCell cell = RecProbCalc(agent,per,permutation.size()-1,inputMatrix);
		ProbabilityCell cell = RecProbCalc(agent,per,0,inputMatrix);
		cell.setCandidates(permutation);
		return cell;
	}

	private static ProbabilityCell RecProbCalc(String agent,String per, int index, OneSettingDistMatrix inputMatrix) {
		
		//Stop if this is the first candidate
		String[] perArray = per.split(",");
		if (perArray.length == 1)
		{
			return new ProbabilityCell(agent, inputMatrix.getSumOfVotes(agent,perArray[0]));
		}
		//step 1: get Probavility for C(n)  = s
		String candidate = perArray[index]+"";
		HashMap<String, RankDist> allProbsEqual= inputMatrix.getProbsForAgentAndCandidate(agent,candidate);
		
		int numberOfVotes = inputMatrix.getNumberOfVotes(agent, candidate);
		Set<String> voter = new HashSet<String>();
		voter.add(agent);
		
		//step 2: calc Probability for C(n) = at most s
		HashMap<String,RankDist> allProbsMost = new HashMap<String, RankDist>();
		DynamicHelper.CalcCandidateVoteCumulative(allProbsMost,allProbsEqual, numberOfVotes, voter);
		
		
		//step 3: Prob that C(n-1) win Cn for each V(Cn-1)
		HashMap<String,RankDist> allProbsIsWinner = new HashMap<String, RankDist>();
		List<String> optionalWinners = new ArrayList<String>();
		optionalWinners.add(perArray[index+1]+""); //- edit
		optionalWinners.add(candidate);
		voter.clear(); voter.add(perArray[index+1]+""); //- edit
		HashMap<String, RankDist> nextCandProbsEqual= inputMatrix.getProbsForAgentAndCandidate(agent,per.split(",")[index+1]+""); //edit -
		DynamicHelper.CalcCandidateProbForWinning(allProbsIsWinner,allProbsMost,nextCandProbsEqual,numberOfVotes, voter ,optionalWinners);
		
		//step 4: do it again for C(n-1)
		inputMatrix.SetAgentProbsFromOther(agent,allProbsIsWinner);
		//return RecProbCalc(agent,Calculations.SubArray(perArray, 0, perArray.length-1),index-1,inputMatrix);
		return RecProbCalc(agent,Calculations.SubArray(perArray, 1, perArray.length),index,inputMatrix);
	}
	
	
}
